var app = getApp();
var utils = require("./util.js");

//带token请求
function userRequest(title, method, url, data, back) {
  wx.showLoading({
    title: title,
  })
  var configUrl = app.config.url;
  var userToken = app.globalData.userToken;
  var userId = app.globalData.userId;
  console.log(configUrl + url);
  wx.request({
    url: configUrl + url,
    method: method,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'X-Login-Token': userToken,
      'X-User-Id': userId
    },
    data: data,
    success: function(res) {
      wx.hideLoading();
      if (res.data.code == 200) {
        back(res.data);
      } else if (res.data.code == 401) {
        app.globalData.isNewUserInfo = false;
        app.globalData.refreshState = false;
        app.globalData.userId = null;
        app.globalData.userInfo=null;
        app.globalData.userToken=null;
        wx.showToast({
          icon: 'none',
          title: "登录超时",
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: res.data.msg,
        })
      }
    },
    fail: function(res) {
      wx.hideLoading();
      back(res)
    }
  })
}

//带token请求
function storeRequest(title, method, url, storeId, data, back) {
  wx.showLoading({
    title: title,
  })
  var configUrl = app.config.url;
  var userToken = app.globalData.userToken;
  var userId = app.globalData.userId;
  console.log(configUrl + url);
  wx.request({
    url: configUrl + url,
    method: method,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'X-Login-Token': userToken,
      'X-User-Id': userId,
      'X-Store-Id': storeId
    },
    data: data,
    success: function(res) {
      wx.hideLoading();
      if (res.data.code == 200) {
        back(res.data);
      } else if (res.data.code == 401) {
        app.globalData.isNewUserInfo = false;
        app.globalData.userId = null;
        app.globalData.userInfo = null;
        app.globalData.userToken = null;
        wx.showToast({
          icon: 'none',
          title: "登录超时",
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: res.data.msg,
        })
      }
    },
    fail: function(res) {
      wx.hideLoading();
      back(res)
    }
  })
}


module.exports = {
  userRequest: userRequest,
  storeRequest: storeRequest
}